package buildings.net.server.sequental;

import buildings.Building;
import buildings.Buildings;
import buildings.dwelling.Dwelling;
import buildings.dwelling.DwellingFactory;
import buildings.dwelling.hotel.Hotel;
import buildings.dwelling.hotel.HotelFactory;
import buildings.net.server.exceptions.BuildingUnderArrestException;
import buildings.office.OfficeBuilding;
import buildings.office.OfficeFactory;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class SerialServer {

    public static void main(String[] args) {
        Socket clientSocket = null;
        while (true) {
            try {
                ServerSocket server = new ServerSocket(6667, 0, InetAddress.getByName("localhost"));
                clientSocket = server.accept();
                ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
                ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
                out.writeObject("HELLO");
                Building buf = null;
                float cost = 0;
                String type = null;
                String str = null;
                while (true) {

                    //определяем, что хочет передать клиент
                    type = in.readUTF();

                    //если клиент прощается, завершаем прием
                    if (type.equals("end")) {
                        break;
                    }

                    //получаем здание
                    try {
                        buf = (Building) in.readObject();
                    } catch (ClassNotFoundException e) {
                        break;
                    }

                    //оцениваем здание
                    try {
                        str = Float.toString(getCost((Dwelling) buf));
                    } catch (BuildingUnderArrestException e) {
                        str = "Здание под арестом!";
                    }

                    out.writeObject(str);
                }
            } catch (IOException e) {
            }
        }
    }

    private static float getCost(Building b)
            throws BuildingUnderArrestException {
        if (!isArested()) {
            if (b instanceof Dwelling) {
                return b.getTotalSquare() * 1000;
            }
            if (b instanceof OfficeBuilding) {
                return b.getTotalSquare() * 1500;
            }
            if (b instanceof Hotel) {
                return b.getTotalSquare() * 2000;
            }
        }
        throw new BuildingUnderArrestException();
    }

    private static boolean isArested() {
        Random r = new Random();
        int buf = r.nextInt(100);
        if (buf < 10) {
            return true;
        }
        return false;
    }
}
